package org.ourguy.mymoviesandshows.httpclient.trakt;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.ourguy.mymoviesandshows.httpclient.GenericHTTPClient;
import org.ourguy.mymoviesandshows.httpclient.HTTPClientException;

import android.text.TextUtils;

/**
 * RESTful client for the Trakt.TV API
 * @author bordjukov
 */
public class TraktRESTClient extends GenericHTTPClient {
	/**
	 * The base URL of the Trakt TV API
	 */
	private static final String API_HOST = "api.trakt.tv";
	
	/**
	 * The port the API listens on.
	 * -1 is default port in accordance to scheme. 
	 */
	private static final int API_PORT = -1;
	
	/**
	 * The API Key needed for communication with the API
	 */
	private static final String API_KEY = "335347e75f49a038e7bbe8ee32a05224";
	
	/**
	 * The API Connection scheme (http/https).
	 * For the time being trakt.tv does not support https.
	 */
	private static final String API_SCHEME = "http";
	
	/**
	 * The default format used by the API
	 */
	private static final String API_FORMAT = "json";
	
	/**
	 * Execute a GET query to an API method that accepts several parameters
	 * @param method The method we are calling
	 * @return The received response
	 * @throws HTTPClientException if something goes wrong
	 */
	public HttpResponse get(String method, String ... params) throws HTTPClientException {
		try {
			HttpResponse response = sendRequest(new HttpGet(getURI(method, params)), null);

			// Validating the response status code
			if (response.getStatusLine().getStatusCode() != 200)
				throw new HTTPClientException("Unacceptable response code received from the server: " +
						response.getStatusLine().getStatusCode());
			
			// Validating the response content type
			// TODO move the accepted content type to a constant
			if (!response.getHeaders("Content-Type")[0].getValue().equals("application/json"))
				throw new HTTPClientException("Unacceptable content encoding received from the server: " +
						response.getHeaders("Content-Type")[0].getValue());
			
			return response;
		} catch (Exception e) {
			throw new HTTPClientException("An exception occured while " +
					"attempting to send the HTTP GET request.", e);
		}
	}
	
	/**
	 * Execute a POST query to the API
	 * @param url The URL we are querying
	 * @param postdata The data we would like to post
	 * @return The received response
	 * @throws HTTPClientException 
	 */
	public HttpResponse post(String method, Object postdata) throws HTTPClientException {
		throw new UnsupportedOperationException("Not supported yet.");
	}
	
	
	
	/**
	 * Get an absolute uri by method name and query parameters
	 * @param method The method we are calling
	 * @param params The parameters we are passing to the method
	 * @return The URI for the request
	 * @throws URISyntaxException 
	 * @throws UnsupportedEncodingException 
	 */
	private static URI getURI(String method, String[] params) throws URISyntaxException, UnsupportedEncodingException {
		String path = String.format("%s.%s/%s", method, API_FORMAT, API_KEY);
		
		if (params.length > 0) {
			for (int i = 0; i < params.length; i++) {
				params[i] = URLEncoder.encode(params[i], "ASCII");
			}
			path = path + "/"+TextUtils.join("/", params);
		}

		URI uri = URIUtils.createURI(API_SCHEME, API_HOST, API_PORT, path, null, null);
		return uri;
	}
}
